/**
 * 订单相关接口-RestFull风格
 * 包括删除订单、查询订单
 */
const express = require('express')
// 创建路由对象
const router = express.Router()
// 引入数据库连接池
const pool = require("../../db/db")
// 引入Joi表单校验
const Joi = require("joi")
// 引入Response
const Response = require("../../utils/ResponseData")

// 订单编号\订单号\用户名称\联系人\联系电话\订单时间\订单价格\订单状态
/**
 * 查询订单列表接口
 * @param page:当前页码
 * @param pageSize:每页显示条数
 * @param keywords:关键字
 */
router.get("/petOrder/get/:page/:pageSize/:keywords", async (req, res) => {
  // 结构前端传过来的数据
  let { page, pageSize, keywords } = req.params
  // 校验规则
  let schema = Joi.object({
    page: Joi.number().required(),
    pageSize: Joi.number().required(),
    keywords: Joi.string().required()
  })
  // 校验
  let { error } = schema.validate(req.params)
  if (error) {
    res.send(Response.error(error))
    return
  }
  try {
    console.log('keywords', keywords) // "''" ''
    if (keywords == "''") keywords = ''
    // 编写sql-查询每页信息
    // 根据当前页和每页显示条数，计算开始位置
    const startIndex = (page - 1) * pageSize
    pageSize = parseInt(pageSize)
    const sql = `
        select 
          po.po_id,
          po.po_number,
          p.p_img,
          p.p_name,
          u.u_name,
          c.name,
          c.tel,
          b.b_name,
          b.b_city_detail,
          po.po_time,
          po.po_price,
          po.po_status 
        from
          pet_po po,
          pet p,
          contact c,
          business b,
          user u 
        where po.pet_id = p.p_id 
          and po.bus_id = b.b_id 
          and c.user_id = u.u_id 
          and p.user_id = u.u_id 
          and (c.name like ? 
            or c.tel like ?)
            limit ?,?
            
        `
    // 执行sql
    let result = await pool.querySync(sql, [`%${keywords}%`, `%${keywords}%`, startIndex, pageSize])

    // 编写sql-查询总条数
    const sql2 = `
        select 
          count(po_id) as count
        from
          (select 
            po.po_id,
            po.po_number,
            p.p_img,
            p.p_name,
            u.u_name,
            c.name,
            c.tel,
            b.b_name,
            b.b_city_detail,
            po.po_time,
            po.po_price,
            po.po_status 
          from
            pet_po po,
            pet p,
            contact c,
            business b,
            user u 
          where po.pet_id = p.p_id 
            and po.bus_id = b.b_id 
            and c.user_id = u.u_id 
            and p.user_id = u.u_id 
            and (c.name like ? 
              or c.tel like ?)) o1
        `
    // 执行sql
    let result2 = await pool.querySync(sql2, [`%${keywords}%`, `%${keywords}%`])
    // 获取总条数
    const total = result2[0].count
    // 计算总页数：总页数 = 总条数%每页显示条数==0?总条数/每页显示条数:总条数/每页显示条数+1
    // 计算总页数：总页数 = Math.ceil(总条数/每页显示条数) 
    const maxPage = Math.ceil(total / pageSize)

    res.send(Response.success({ page, pageSize, total, maxPage, result }))
  } catch (e) {
    res.send(Response.error(e))
  }
})


module.exports = router
